package com.example.ruihuada.widget.webEditor;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;


/**
 * A text editor WebView with support for JavaScript execution.
 */
public abstract class EditorWebViewAbstract extends WebView {
    public abstract void execJavaScriptFromString(String javaScript);

    private ErrorListener mErrorListener;

    public EditorWebViewAbstract(Context context, AttributeSet attrs) {
        super(context, attrs);
        configureWebView();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void configureWebView() {


//        WebSettings settings = getSettings();           //和系统webview一样
//        settings.setJavaScriptEnabled(true);                    //支持Javascript 与js交互
//        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
//        settings.setAllowFileAccess(true);                      //设置可以访问文件
//        settings.setSupportZoom(true);                          //支持缩放
//        settings.setBuiltInZoomControls(true);                  //设置内置的缩放控件
//        settings.setUseWideViewPort(true);                      //自适应屏幕
//        settings.setSupportMultipleWindows(true);               //多窗口
//        settings.setDefaultTextEncodingName("utf-8");            //设置编码格式
//        settings.setAppCacheEnabled(true);
//        settings.setDomStorageEnabled(true);
//        settings.setAppCacheMaxSize(Long.MAX_VALUE);
//        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);       //缓存模式
//        setWebViewClient(new WebViewClient() {
//
//            @Override
//            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
//                super.onPageStarted(webView, s, bitmap);
//            }
//
//            @Override
//            public void onPageFinished(WebView webView, String s) {
//                super.onPageFinished(webView, s);
//            }
//
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
//                webView.loadUrl(url);
//                return true;
//            }
//
//            @Override
//            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
////                super.onReceivedSslError(webView, sslErrorHandler, sslError);
//                sslErrorHandler.proceed();//忽略SSL证书错误
//            }
//        });
//
//        setWebChromeClient(new WebChromeClient() {
//            @Override
//            public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
//                return super.onJsAlert(webView, s, s1, jsResult);
//            }
//
//            @Override
//            public void onReceivedTitle(WebView webView, String s) {
//                super.onReceivedTitle(webView, s);
//            }
//
//            @Override
//            public void onProgressChanged(WebView webView, int progress) {
//                super.onProgressChanged(webView, progress);
//
//            }
//        });
        WebSettings webSettings = this.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");

        this.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                if (url != null && url.startsWith("callback") && mJsCallbackReceiver != null) {
//                    String data = URLDecoder.decode(url);
//                    String[] split = data.split(":", 2);
//                    String callbackId = split[0];
//                    String params = (split.length > 1 ? split[1] : "");
//                    mJsCallbackReceiver.executeCallback(callbackId, params);
//                }
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            }


        });

        this.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(@NonNull ConsoleMessage cm) {
                if (cm.messageLevel() == ConsoleMessage.MessageLevel.ERROR) {
                    if (mErrorListener != null) {
                        mErrorListener.onJavaScriptError(cm.sourceId(), cm.lineNumber(), cm.message());
                    }

                }
                return true;
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

                if (mErrorListener != null) {
                    mErrorListener.onJavaScriptAlert(url, message);
                }
                return true;
            }
        });
    }

    @Override
    public boolean onCheckIsTextEditor() {
        return true;
    }

    @Override
    public void setVisibility(int visibility) {
        notifyVisibilityChanged(visibility == View.VISIBLE);
        super.setVisibility(visibility);
    }

    /**
     * Handles events that should be triggered when the WebView is hidden or is shown to the user
     *
     * @param visible the new visibility status of the WebView
     */
    public void notifyVisibilityChanged(boolean visible) {
        if (!visible) {
            this.post(new Runnable() {
                @Override
                public void run() {
                    execJavaScriptFromString("ZSSEditor.pauseAllVideos();");
                }
            });
        }
    }


    public interface ErrorListener {
        void onJavaScriptError(String sourceFile, int lineNumber, String message);

        void onJavaScriptAlert(String url, String message);
    }
}
